public class DeadLockDemo2 {
    private static Object pen = new Object();
    private static Object book = new Object();

    public static void main(String[] args) {
        new Thread(()-> {
            synchronized (pen) {
                System.out.println(Thread.currentThread().getName() + "拿了pen");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "等待拿book");
                synchronized (book) {
                    System.out.println(Thread.currentThread().getName() + "拿了book");
                }
            }
        }, "小红").start();

        new Thread(()->{
            synchronized (book){
                System.out.println(Thread.currentThread().getName() + "拿到了book");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "等待拿pen");
                synchronized (pen){
                    System.out.println(Thread.currentThread().getName() + "拿到了book");
                }
            }
        }, "小王").start();
    }
}
